<template>
    <div class="app-container">
        <el-row :gutter="20">
            <div>
            </div>
            <el-col :xs="9" :sm="6" :md="5" :lg="4" :xl="4">
                <el-button class="filter-item" size="mini" type="primary" icon="el-icon-plus" @click="addTree(1)"
                    :disabled="addDisabled"></el-button>
                <el-button class="filter-item" size="mini" type="success" icon="el-icon-edit" @click="addTree(2)"
                    :disabled="updateDelelteDisabled"></el-button>
                <el-button class="filter-item" type="danger" icon="el-icon-delete" size="mini" @click="deleteTree()"
                    :disabled="updateDelelteDisabled"></el-button>
                <el-tree :expand-on-click-node="false" style="max-width: 600px" :data="treeData" :props="defaultProps"
                    @node-click="handleNodeClick" />

                <el-dialog :visible.sync="dialogFormVisibleAdd" :close-on-click-modal="false" @close="cancel2()"
                    :title="addTitle + addName">
                    <el-row :gutter="15">
                        <el-form ref="form" :model="treefrom" :rules="rules" size="medium" label-width="100px">
                            <el-col :span="18">
                                <el-form-item :label="addTitle + '编码'" prop="code">
                                    <el-input v-model="treefrom.code" clearable :style="{ width: '100%' }"></el-input>
                                </el-form-item>
                            </el-col>
                            <el-col :span="18">
                                <el-form-item :label="addTitle + '名称'" prop="name">
                                    <el-input v-model="treefrom.name" placeholder="请输入区域名称" clearable
                                        :style="{ width: '100%' }"></el-input>
                                </el-form-item>
                            </el-col>
                            <!-- <el-col :span="18">
                                <el-form-item label="父级" prop="pCode">
                                    <el-input v-model="treefrom.pCode" placeholder="请输入父级" clearable
                                        :style="{ width: '100%' }"></el-input>
                                </el-form-item>
                            </el-col> -->
                        </el-form>
                    </el-row>
                    <div slot="footer">
                        <el-button size="small" type="text" @click="cancel2">取消</el-button>
                        <el-button size="small" v-loading="formLoading" type="primary" @click="saveTree">确认</el-button>
                    </div>
                </el-dialog>

            </el-col>
            <el-col :xs="15" :sm="18" :md="19" :lg="20" :xl="20">

                <div class="head-container">
                    <!-- 搜索 -->
                    <!-- <el-input v-model="listQuery.Filter" clearable size="small" placeholder="搜索..."
                        style="width: 200px;" class="filter-item" @keyup.enter.native="handleFilter" />
                    <el-button class="filter-item" size="mini" type="success" icon="el-icon-search"
                        @click="handleFilter">搜索</el-button> -->
                    <el-button class="filter-item" size="mini" type="primary" icon="el-icon-plus" @click="handleCreate"
                        :disabled="addLocationDisabled">新增</el-button>
                    <el-button class="filter-item" size="mini" type="success" icon="el-icon-edit"
                        @click="handleUpdate()">修改</el-button>
                    <el-button slot="reference" class="filter-item" type="danger" icon="el-icon-delete" size="mini"
                        @click="handleDelete()">删除</el-button>
                    <!-- 导出 -->
                    <el-button class="filter-item" size="mini" type="info" icon="el-icon-download"
                        @click="handleExport()">导出</el-button>
                    <!-- 导入 -->
                    <el-button class="filter-item" size="mini" type="info" icon="el-icon-upload"
                        @click="handleImport()">导入</el-button>
                    <input type="file" id="file" accept=".xls,.xlsx" @change="onFileChange" />
                </div>
                <el-dialog :visible.sync="dialogFormVisible" :close-on-click-modal="false" @close="cancel()"
                    :title="formTitle">
                    <el-row :gutter="15">
                        <el-form ref="form" :model="form" :rules="rules" size="medium" label-width="100px">
                            <!-- <el-col :span="23">
                                <el-form-item label="父级" prop="pCode">
                                    <el-input v-model="form.pCode" placeholder="请选择父级" clearable
                                        :style="{ width: '100%' }"></el-input>
                                </el-form-item>
                            </el-col> -->
                            <el-col :span="8">
                                <el-form-item label="库位编码" prop="code">
                                    <el-input v-model="form.code" placeholder="请输入库位编码" clearable
                                        :style="{ width: '100%' }"></el-input>
                                </el-form-item>
                            </el-col>
                            <el-col :span="8">
                                <el-form-item label="库位类型" prop="locationType">
                                    <el-select v-model="form.locationType" placeholder="请输入库位类型"
                                        :style="{ width: '100%' }">
                                        <el-option v-for="(item, index) in LocationTypeOptions" :key="index"
                                            :label="item.label" :value="item.value"
                                            :disabled="item.disabled"></el-option>
                                    </el-select>
                                </el-form-item>
                            </el-col>
                            <el-col :span="8">
                                <el-form-item label="使用方式" prop="usePattern">
                                    <el-select v-model="form.usePattern" placeholder="请选择使用方式"
                                        :style="{ width: '100%' }">
                                        <el-option v-for="(item, index) in UsePatternOptions" :key="index"
                                            :label="item.label" :value="item.value"
                                            :disabled="item.disabled"></el-option>
                                    </el-select>
                                </el-form-item>
                            </el-col>
                            <el-col :span="8">
                                <el-form-item label="库位长" prop="locationLength">
                                    <el-input v-model="form.locationLength" placeholder="请输入库位长" clearable
                                        :style="{ width: '100%' }" @focus="setLocationLengthValueFocus(1)"
                                        @blur="setLocationLengthValueBlur(1)"></el-input>
                                </el-form-item>
                            </el-col>
                            <el-col :span="8">
                                <el-form-item label="库位宽" prop="locationWidth">
                                    <el-input v-model="form.locationWidth" placeholder="请输入库位宽" clearable
                                        :style="{ width: '100%' }" @focus="setLocationLengthValueFocus(2)"
                                        @blur="setLocationLengthValueBlur(2)"></el-input>
                                </el-form-item>
                            </el-col>
                            <el-col :span="8">
                                <el-form-item label="库位高" prop="locationHeight">
                                    <el-input v-model="form.locationHeight" placeholder="请输入库位高" clearable
                                        :style="{ width: '100%' }" @focus="setLocationLengthValueFocus(3)"
                                        @blur="setLocationLengthValueBlur(3)"></el-input>
                                </el-form-item>
                            </el-col>
                            <el-col :span="8">
                                <el-form-item label="库位容积" prop="locationVolume">
                                    <el-input v-model="form.locationVolume" placeholder="请输入库位容积" clearable
                                        :style="{ width: '100%' }" @focus="setLocationLengthValueFocus(4)"
                                        @blur="setLocationLengthValueBlur(4)"></el-input>
                                </el-form-item>
                            </el-col>
                            <el-col :span="8">
                                <el-form-item label="库位承重" prop="loadBearing">
                                    <el-input v-model="form.loadBearing" placeholder="请输入库位承重" clearable
                                        :style="{ width: '100%' }" @focus="setLocationLengthValueFocus(5)"
                                        @blur="setLocationLengthValueBlur(5)"></el-input>
                                </el-form-item>
                            </el-col>
                            <el-col :span="8">
                                <el-form-item label="锁定优先级" prop="lockPriority">
                                    <el-input v-model="form.lockPriority" placeholder="请输入锁定优先级" clearable
                                        :style="{ width: '100%' }"></el-input>
                                </el-form-item>
                            </el-col>
                            <el-col :span="16">
                                <el-form-item label="优先商品" prop="priorityGoods">
                                    <el-input v-model="form.priorityGoods" placeholder="请输入优先商品" clearable
                                        :style="{ width: '100%' }"></el-input>
                                </el-form-item>
                            </el-col>
                            <!-- <el-col :span="8">
                                <el-form-item label="已用容积" prop="usedVolume">
                                    <el-input v-model="form.usedVolume" placeholder="请输入已用容积" clearable
                                        :style="{ width: '100%' }"></el-input>
                                </el-form-item>
                            </el-col>
                            <el-col :span="8">
                                <el-form-item label="已用承重" prop="usedLoadBearing">
                                    <el-input v-model="form.usedLoadBearing" placeholder="请输入已用承重" clearable
                                        :style="{ width: '100%' }"></el-input>
                                </el-form-item>
                            </el-col>
                            <el-col :span="8">
                                <el-form-item label="巷号" prop="laneway">
                                    <el-input v-model="form.laneway" placeholder="请输入巷号" clearable
                                        :style="{ width: '100%' }"></el-input>
                                </el-form-item>
                            </el-col>
                            <el-col :span="8">
                                <el-form-item label="货架号" prop="goodsShelf">
                                    <el-input v-model="form.goodsShelf" placeholder="请输入货架号" clearable
                                        :style="{ width: '100%' }"></el-input>
                                </el-form-item>
                            </el-col>
                            <el-col :span="8">
                                <el-form-item label="层号" prop="layer">
                                    <el-input v-model="form.layer" placeholder="请输入层号" clearable
                                        :style="{ width: '100%' }"></el-input>
                                </el-form-item>
                            </el-col>
                            <el-col :span="8">
                                <el-form-item label="位号" prop="place">
                                    <el-input v-model="form.place" placeholder="请输入位号" clearable
                                        :style="{ width: '100%' }"></el-input>
                                </el-form-item>
                            </el-col>
                            <el-col :span="8">
                                <el-form-item label="路径优先级" prop="pathPriority">
                                    <el-input v-model="form.pathPriority" placeholder="请输入路径优先级" clearable
                                        :style="{ width: '100%' }"></el-input>
                                </el-form-item>
                            </el-col>
                            <el-col :span="8">
                                <el-form-item label="库位标签" prop="locationLabel">
                                    <el-input v-model="form.locationLabel" placeholder="请输入库位标签" clearable
                                        :style="{ width: '100%' }"></el-input>
                                </el-form-item>
                            </el-col>
                            <el-col :span="8">
                                <el-form-item label="库位异常" prop="locationException">
                                    <el-input v-model="form.locationException" placeholder="请输入库位异常" clearable
                                        :style="{ width: '100%' }"></el-input>
                                </el-form-item>
                            </el-col>


                            <el-col :span="8">
                                <el-form-item label="是否混放" prop="isMixing">
                                    <el-select v-model="form.isMixing" placeholder="请选择是否混放" clearable
                                        :style="{ width: '100%' }">
                                        <el-option v-for="(item, index) in IsMixingOptions" :key="index"
                                            :label="item.label" :value="item.value"
                                            :disabled="item.disabled"></el-option>
                                    </el-select>
                                </el-form-item>
                            </el-col>
                            <el-col :span="8">
                                <el-form-item label="排除指导余量" prop="exclusionMargin">
                                    <el-select v-model="form.exclusionMargin" placeholder="请选择排除指导余量" clearable
                                        :style="{ width: '100%' }">
                                        <el-option v-for="(item, index) in ExclusionMarginOptions" :key="index"
                                            :label="item.label" :value="item.value"
                                            :disabled="item.disabled"></el-option>
                                    </el-select>
                                </el-form-item>
                            </el-col>
                            <el-col :span="8">
                                <el-form-item label="排除指导历史" prop="exclusionHistory">
                                    <el-select v-model="form.exclusionHistory" placeholder="请选择排除指导历史" clearable
                                        :style="{ width: '100%' }">
                                        <el-option v-for="(item, index) in ExclusionHistoryOptions" :key="index"
                                            :label="item.label" :value="item.value"
                                            :disabled="item.disabled"></el-option>
                                    </el-select>
                                </el-form-item>
                            </el-col> -->
                        </el-form>
                    </el-row>
                    <div slot="footer">
                        <el-button size="small" type="text" @click="cancel">取消</el-button>
                        <el-button size="small" v-loading="formLoading" type="primary" @click="save">确认</el-button>
                    </div>
                </el-dialog>
                <!-- v-loading="listLoading"  -->
                <el-table ref="multipleTable" :data="list" size="small" style="width: 90%;" @sort-change="sortChange"
                    @selection-change="handleSelectionChange" @row-click="handleRowClick">
                    <el-table-column type="selection" width="44px"></el-table-column>
                    <el-table-column label="库区名称" prop="warehouseAreaName" align="center" />
                    <el-table-column label="库位编码" prop="code" align="center" />
                    <el-table-column label="库位类型" prop="locationType" align="center">
                        <template v-slot="scope">
                            <span>{{ getWarehouseLocationTypeName(scope.row.locationType) }}</span>
                        </template>
                    </el-table-column>
                    <el-table-column label="使用方式" prop="usePattern" align="center">
                        <template v-slot="scope">
                            <span>{{ getWarehouseUsePatternName(scope.row.usePattern) }}</span>
                        </template>
                    </el-table-column>
                    <el-table-column label="库位长" prop="locationLength" align="center">
                        <template v-slot="scope">
                            <span>{{ scope.row.locationLength }}m</span>
                        </template>
                    </el-table-column>
                    <el-table-column label="库位宽" prop="locationWidth" align="center">
                        <template v-slot="scope">
                            <span>{{ scope.row.locationWidth }}m</span>
                        </template>
                    </el-table-column>
                    <el-table-column label="库位高" prop="locationHeight" align="center">
                        <template v-slot="scope">
                            <span>{{ scope.row.locationHeight }}m</span>
                        </template>
                    </el-table-column>
                    <el-table-column label="库位容积" prop="locationVolume" align="center">
                        <template v-slot="scope">
                            <span>{{ scope.row.locationVolume }}m³</span>
                        </template>
                    </el-table-column>
                    <el-table-column label="已用容积" prop="usedVolume" align="center">
                        <template v-slot="scope">
                            <span>{{ scope.row.usedVolume }}m³</span>
                        </template>
                    </el-table-column>
                    <el-table-column label="库位承重" prop="loadBearing" align="center">
                        <template v-slot="scope">
                            <span>{{ scope.row.loadBearing }}kg</span>
                        </template>
                    </el-table-column>
                    <el-table-column label="已用承重" prop="usedLoadBearing" align="center">
                        <template v-slot="scope">
                            <span>{{ scope.row.usedLoadBearing }}kg</span>
                        </template>
                    </el-table-column>
                    <el-table-column label="巷道号" prop="laneway" align="center" />
                    <el-table-column label="货架号" prop="goodsShelf" align="center" />
                    <el-table-column label="层号" prop="layer" align="center" />
                    <el-table-column label="位号" prop="place" align="center" />
                    <el-table-column label="货品混放" prop="isMixing" align="center">
                        <template v-slot="scope">
                            <span>{{ scope.row.isMixing == 1 ? '是' : '否' }}</span>
                        </template>
                    </el-table-column>
                    <el-table-column label="锁定优先级" prop="lockPriority" align="center" />
                    <el-table-column label="路径优先级" prop="pathPriority" align="center" />
                    <el-table-column label="库位标签" prop="locationLabel" align="center" />
                    <el-table-column label="库位异常" prop="locationException" align="center" />
                    <el-table-column label="优先商品" prop="priorityGoods" align="center" />
                    <el-table-column label="排除指导余量" prop="exclusionMargin" align="center">
                        <template v-slot="scope">
                            <el-switch v-model="scope.row.exclusionMargin == '1' ? true : false" active-color="#13ce66"
                                inactive-color="">
                            </el-switch>
                        </template>
                    </el-table-column>
                    <el-table-column label="排除指导历史" prop="exclusionHistory" align="center">
                        <template v-slot="scope">
                            <el-switch v-model="scope.row.exclusionHistory == '1' ? true : false" active-color="#13ce66"
                                inactive-color="">
                            </el-switch>
                        </template>
                    </el-table-column>
                    <!-- <el-table-column label="操作" align="center">
                        <template slot-scope="{row}">
                            <el-button type="primary" size="mini" @click="handleUpdate(row)" icon="el-icon-edit" />
                            <el-button type="danger" size="mini" @click="handleDelete(row)" icon="el-icon-delete" />
                        </template>
                    </el-table-column> -->
                </el-table>
                <pagination v-show="totalCount > 0" :total="totalCount" :page.sync="page"
                    :limit.sync="listQuery.MaxResultCount" @pagination="getList" />
            </el-col>
        </el-row>
    </div>

</template>
<script>
import Pagination from "@/components/Pagination";
import permission from "@/directive/permission/index.js";
import axios from "axios";
const defaultForm = {
    id: null,
    pCode: null,
    code: null,
    locationLength: '0',
    locationWidth: '0',
    locationHeight: '0',
    locationVolume: '0',
    loadBearing: '0',
    lockPriority: "",
    priorityGoods: "",
    usedVolume: '0',
    usedLoadBearing: '0',
    laneway: "",
    goodsShelf: "",
    layer: "",
    place: "",
    pathPriority: "",
    locationLabel: "",
    LocationException: "",
    locationType: "1",
    usePattern: "1",
    isMixing: '0',
    exclusionMargin: '0',
    exclusionHistory: '0',
}
export default {
    name: 'WarehouseLocation',
    components: {
        Pagination
    },
    directives: {
        permission
    },
    props: [],
    data() {
        return {
            //#region 树型所需数据
            treefrom: {
                id: "",
                code: "",
                pCode: "",
                name: ""
            },
            isAdd: true,
            addDisabled: true,
            updateDelelteDisabled: true,
            addName: "",
            addTitle: "",
            dialogFormVisibleAdd: false,  //打开新增弹窗或修改
            onTreeData: null, //点击树型结构 获取的 数据
            treeData: null, // 树型结构数据
            defaultProps: {         // 树型结构配置
                children: 'children',
                label: 'label',
            },
            //#endregion
            //#region 库位所需数据

            addLocationDisabled: true,
            rules: {
                pCode: [],
                code: [{
                    required: true,
                    message: '请输入库位编码',
                    trigger: 'blur'
                }],
                locationLength: [{
                    required: true,
                    message: '请输入库位长',
                    trigger: 'blur'
                }],
                locationWidth: [{
                    required: true,
                    message: '请输入库位宽',
                    trigger: 'blur'
                }],
                locationHeight: [{
                    required: true,
                    message: '请输入库位高',
                    trigger: 'blur'
                }],
                locationVolume: [{
                    required: true,
                    message: '请输入库位容积',
                    trigger: 'blur'
                }],
                loadBearing: [
                    { required: true, message: '请输入库位承重', trigger: 'blur' },
                ],
                lockPriority: [
                    { required: true, message: '请输入锁定优先级', trigger: 'blur' },
                ],
                priorityGoods: [
                    { required: true, message: '请输入优先商品', trigger: 'blur' },
                ],
                usedVolume: [],
                usedLoadBearing: [],
                laneway: [],
                goodsShelf: [],
                layer: [],
                place: [],
                pathPriority: [],
                locationLabel: [],
                locationException: [],
                locationType: [],
                usePattern: [],
                isMixing: [],
                exclusionMargin: [],
                exclusionHistory: [],
            },
            form: Object.assign({}, defaultForm),
            list: null,

            totalCount: 0,
            listLoading: true,
            formLoading: false,
            listQuery: {
                WarehouseId: "",
                AreaId: "",
                Filter: '',
                Sorting: '',
                SkipCount: 0,
                MaxResultCount: 10
            },
            page: 1,
            dialogFormVisible: false,
            multipleSelection: [],
            formTitle: '',
            isEdit: false,
            LocationTypeOptions: [], //库位类型选项
            UsePatternOptions: [], //库位使用方式选项
            IsMixingOptions: [{
                "label": "是",
                "value": "1"
            }, {
                "label": "否",
                "value": "0"
            }],
            ExclusionMarginOptions: [{
                "label": "是",
                "value": "1"
            }, {
                "label": "否",
                "value": "0"
            }],
            ExclusionHistoryOptions: [{
                "label": "是",
                "value": "1"
            }, {
                "label": "否",
                "value": "0"
            }],
            file: null,
            //#endregion
        }
    },
    computed: {},
    watch: {
        'form.locationLength': 'calculateVolume',
        'form.locationWidth': 'calculateVolume',
        'form.locationHeight': 'calculateVolume'
    },
    created() {
        // this.getList()
        this.getTreeData()  // 获取树型结构数据
        this.getWarehouseLocationTypeOptions()  // 获取库位类型选项
        this.getWarehouseUsePatternOptions()  // 获取库位使用方式选项

    },
    mounted() { },
    methods: {
        //
        onFileChange(file) {
            this.file = file.target.files[0]; //获取上传的文件
        },
        //导入
        handleImport() {
            if (!this.file) {
                this.$notify({
                    title: '失败',
                    message: '请选择文件',
                    type: 'error',
                    duration: 2000
                });
                return;
            }
            const formData = new FormData();
            formData.append('file', this.file);
            axios({
                url: 'http://localhost:62162/api/business/warehouseLocation/ImportExcel', // 请将此 URL 替换为你的服务器导出 Excel 的接口地址
                method: 'POST',
                data: formData,
                headers: { 'Content-Type': 'multipart/form-data' }
            }).then((response) => {
                this.$notify({
                    title: '成功',
                    message: '导入成功',
                    type: 'success',
                    duration: 2000
                });
                window.location.reload();
            }).catch((error) => {
                console.error('导入 Excel 时出错:', error);
            });
        },

        //导出
        handleExport() {
            axios({
                url: 'http://localhost:62162/api/business/warehouseLocation/ExportAll', // 请将此 URL 替换为你的服务器导出 Excel 的接口地址
                method: 'GET',
                params: {
                    WarehouseId: this.listQuery.WarehouseId,
                    AreaId: this.listQuery.AreaId,
                    Filter: this.listQuery.Filter,
                    Sorting: this.listQuery.Sorting,
                    SkipCount: this.listQuery.SkipCount,
                    MaxResultCount: this.listQuery.MaxResultCount
                },
                responseType: 'blob'
            }).then((response) => {
                const blob = new Blob([response.data], { type: 'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet' });
                const url = window.URL.createObjectURL(blob);
                const a = document.createElement('a');
                a.href = url;
                a.download = '库位信息.xlsx';
                a.click();
                window.URL.revokeObjectURL(url);
                this.$notify({
                    title: '成功',
                    message: '导出成功',
                    type: 'success',
                    duration: 2000
                });
            }).catch((error) => {
                console.error('导出 Excel 时出错:', error);
            });
        },

        //#region 树型结构
        //删除树型节点
        deleteTree() {
            var params = [];
            params.push(this.onTreeData.id);
            this.$confirm('是否删除该节点?', '提示', {
                confirmButtonText: '确定',
                cancelButtonText: '取消',
                type: 'warning'
            }).then(() => {
                if (this.onTreeData.grade == "[区域]") {
                    this.$axios.posts('/api/business/area/delete', params).then(response => {
                        this.$notify({
                            title: '成功',
                            message: '删除成功',
                            type: 'success',
                            duration: 2000
                        });
                        this.getTreeData();
                    });
                } else {
                    this.$axios.posts('/api/business/WarehouseArea/delete', params).then(response => {
                        this.$notify({
                            title: '成功',
                            message: '删除成功',
                            type: 'success',
                            duration: 2000
                        });
                        this.getTreeData();
                    });
                }

            }).catch(() => {
                this.$message({
                    type: 'info',
                    message: '已取消删除'
                });
            });
        },
        //保存树型结构
        saveTree() {
            this.treefrom.roleNames = this.checkedRole;
            if (this.isAdd) {
                if (this.onTreeData.grade == "[仓库]") {
                    this.$axios.posts('/api/business/area/data-post', this.treefrom).then(response => {
                        this.formLoading = false;
                        this.$notify({
                            title: '成功',
                            message: '新增成功',
                            type: 'success',
                            duration: 2000
                        });
                        this.dialogFormVisibleAdd = false;
                        this.getTreeData();
                    }).catch(() => {
                        this.formLoading = false;
                    });
                } else {
                    this.$axios.posts('/api/business/WarehouseArea/data-post', this.treefrom).then(response => {
                        this.formLoading = false;
                        this.$notify({
                            title: '成功',
                            message: '新增成功',
                            type: 'success',
                            duration: 2000
                        });
                        this.dialogFormVisibleAdd = false;
                        this.getTreeData();
                    }).catch(() => {
                        this.formLoading = false;
                    });
                }
            } else {
                if (this.onTreeData.grade == "[区域]") {
                    this.$axios.posts('/api/business/area/data-post', this.treefrom).then(response => {
                        this.formLoading = false;
                        this.$notify({
                            title: '成功',
                            message: '更新成功',
                            type: 'success',
                            duration: 2000
                        });
                        this.dialogFormVisibleAdd = false;
                        this.getTreeData();
                    }).catch(() => {
                        this.formLoading = false;
                    });
                } else {
                    this.$axios.posts('/api/business/WarehouseArea/data-post', this.treefrom).then(response => {
                        this.formLoading = false;
                        this.$notify({
                            title: '成功',
                            message: '更新成功',
                            type: 'success',
                            duration: 2000
                        });
                        this.dialogFormVisibleAdd = false;
                        this.getTreeData();
                    }).catch(() => {
                        this.formLoading = false;
                    });
                }
            }
        },
        // 新增弹窗取消按钮
        cancel2() {
            this.clearForm();
            this.dialogFormVisibleAdd = false;
            this.$refs.form.clearValidate();
        },
        //弹框值清空
        clearForm() {
            this.treefrom.id = "";
            this.treefrom.code = "";
            this.treefrom.pCode = "";
            this.treefrom.name = "";
        },
        // 打开新增弹窗或修改
        addTree(number) {
            this.clearForm();
            if (number == 1) {
                this.addName = "新增";
                this.isAdd = true;
                if (this.onTreeData.grade == "[仓库]") {
                    this.addTitle = "区域";
                } else {
                    this.addTitle = "库区";
                }
                this.treefrom.pCode = this.onTreeData.id;
            } else {
                this.addName = "修改";
                this.isAdd = false;
                if (this.onTreeData.grade == "[区域]") {
                    this.addTitle = "区域";
                } else {
                    this.addTitle = "库区";
                }
                this.treefrom.pCode = this.onTreeData.pid;
                this.treefrom.id = this.onTreeData.id;
                this.treefrom.name = this.onTreeData.label.substring(5, this.onTreeData.label.length);
                this.treefrom.code = this.onTreeData.code;
            }
            this.dialogFormVisibleAdd = true;
        },

        // 树型结构点击事件
        handleNodeClick(data) {
            // 输出父节点ID
            this.onTreeData = data;
            console.log("当前ID:", data.id);
            const pid = data.pid;  // 获取当前节点的父节点ID
            const parentNode = this.findParentNode(this.treeData, pid);
            if (parentNode) {
                console.log('父节点ID:', parentNode.id);
                // 获取父级的父级ID
                const grandParentNode = this.findParentNode(this.treeData, parentNode.pid);
                if (grandParentNode) {
                    console.log('父级的父级ID:', grandParentNode.id);  // 输出父级的父级ID
                } else {
                    console.log('未找到父级的父级');
                }
            } else {
                console.log('未找到父节点');
            }
            this.listQuery.WarehouseId = "";
            this.listQuery.AreaId = "";
            this.listQuery.Filter = "";
            if (data.grade == "[仓库]") {
                this.addDisabled = false;
                this.updateDelelteDisabled = true;
                this.listQuery.WarehouseId = data.id;
                this.addLocationDisabled = true;
            } else if (data.grade == "[区域]") {
                this.addDisabled = false;
                this.updateDelelteDisabled = false;
                this.listQuery.AreaId = data.id;
                this.addLocationDisabled = true;
            } else {
                this.addDisabled = true;
                this.updateDelelteDisabled = false;
                this.listQuery.Filter = data.id;
                this.addLocationDisabled = false;
            }
            this.getList()
        },

        // 辅助方法：递归查找父节点
        findParentNode(treeData, pid) {
            for (let node of treeData) {
                // 如果当前节点正是父节点
                if (node.id === pid) {
                    return node;
                }
                // 递归查找子节点
                if (node.children) {
                    const foundNode = this.findParentNode(node.children, pid);
                    if (foundNode) {
                        return foundNode;
                    }
                }
            }
            return null;  // 如果未找到父节点，返回null
        },

        // 树型结构数据获取
        getTreeData() {
            this.$axios.gets('/api/business/Warehouse/data').then(response => {
                this.treeData = response.items;
            });
        },
        //#endregion
        //#region 库位相关

        //#region 下拉框绑定
        getWarehouseUsePatternName(id) {
            const Type = this.UsePatternOptions.find(item => item.value === id);
            return Type ? Type.label : '';
        },
        getWarehouseLocationTypeName(id) {
            const Type = this.LocationTypeOptions.find(item => item.value === id);
            return Type ? Type.label : '';
        },
        getWarehouseUsePatternOptions() {
            this.$axios.gets('/api/base/dictDetails/all?Pid=bbfa6a87-7fbb-9bd1-3727-3a16c1552f15').then(response => {
                this.UsePatternOptions = response.items.map(item => {
                    return {
                        label: item.label,
                        value: (item.value),
                        disabled: false
                    }
                })
            });
        },
        getWarehouseLocationTypeOptions() {
            this.$axios.gets('/api/base/dictDetails/all?Pid=4d788820-c27c-3b2f-c141-3a16c156fc05').then(response => {
                this.LocationTypeOptions = response.items.map(item => {
                    return {
                        label: item.label,
                        value: (item.value),
                        disabled: false
                    }
                })
            });
        },
        //#endregion

        //#region 新增修改默认值
        calculateVolume() {
            const length = parseFloat(this.form.locationLength) || 0;
            const width = parseFloat(this.form.locationWidth) || 0;
            const height = parseFloat(this.form.locationHeight) || 0;

            // 计算容积并更新
            this.form.locationVolume = length * width * height;
        },
        //长、宽、高、容积、承重 加单位
        // setLocationLengthValueFocus(number) {
        //     if (number == 1) {
        //         if (this.form.locationLength !== '' && this.form.locationLength.endsWith('m')) {
        //             this.form.locationLength = this.form.locationLength.slice(0, -1); // 去掉最后一个字符 'm'
        //         }
        //     } else if (number == 2) {
        //         if (this.form.locationWidth !== '' && this.form.locationWidth.endsWith('m')) {
        //             this.form.locationWidth = this.form.locationWidth.slice(0, -1); // 去掉最后一个字符 'm'
        //         }
        //     } else if (number == 3) {
        //         if (this.form.locationHeight !== '' && this.form.locationHeight.endsWith('m')) {
        //             this.form.locationHeight = this.form.locationHeight.slice(0, -1); // 去掉最后一个字符 'm'
        //         }
        //         // } else if (number == 4) {
        //         //     if (this.form.locationVolume !== '' && this.form.locationVolume.endsWith('m³')) {
        //         //         this.form.locationVolume = this.form.locationVolume.slice(0, -2); // 去掉最后三个字符 'm³'
        //         //     }
        //     } else if (number == 5) {
        //         if (this.form.loadBearing !== '' && this.form.loadBearing.endsWith('kg')) {
        //             this.form.loadBearing = this.form.loadBearing.slice(0, -2); // 去掉最后两个字符 'kg'
        //         }
        //     }

        // },
        // setLocationLengthValueBlur(number) {
        //     if (number == 1) {
        //         if (this.form.locationLength === '') {
        //             this.form.locationLength = '0m';
        //         }
        //         if (this.form.locationLength && !this.form.locationLength.endsWith('m')) {
        //             this.form.locationLength += 'm'; // 如果不为空且没有单位，则添加单位
        //         }
        //     } else if (number == 2) {
        //         if (this.form.locationWidth === '') {
        //             this.form.locationWidth = '0m';
        //         }
        //         if (this.form.locationWidth && !this.form.locationWidth.endsWith('m')) {
        //             this.form.locationWidth += 'm'; // 如果不为空且没有单位，则添加单位
        //         }
        //     } else if (number == 3) {
        //         if (this.form.locationHeight === '') {
        //             this.form.locationHeight = '0m';
        //         }
        //         if (this.form.locationHeight && !this.form.locationHeight.endsWith('m')) {
        //             this.form.locationHeight += 'm'; // 如果不为空且没有单位，则添加单位
        //         }
        //         // } else if (number == 4) {
        //         //     if (this.form.locationVolume === '') {
        //         //         this.form.locationVolume = '0m³';
        //         //     }
        //         //     if (this.form.locationVolume && !this.form.locationVolume.endsWith('m³')) {
        //         //         this.form.locationVolume += 'm³'; // 如果不为空且没有单位，则添加单位
        //         //     }
        //     } else if (number == 5) {
        //         if (this.form.loadBearing === '') {
        //             this.form.loadBearing = '0kg';
        //         }
        //         if (this.form.loadBearing && !this.form.loadBearing.endsWith('kg')) {
        //             this.form.loadBearing += 'kg'; // 如果不为空且没有单位，则添加单位
        //         }
        //     }

        // },

        //#endregion

        getList() {
            this.listLoading = true;
            this.listQuery.SkipCount = (this.page - 1) * this.listQuery.MaxResultCount;
            this.$axios.gets('/api/business/warehouseLocation', this.listQuery).then(response => {
                this.list = response.items;
                this.totalCount = response.totalCount;
                this.listLoading = false;
            });
        },
        fetchData(id) {
            this.$axios.gets('/api/business/warehouseLocation/' + id).then(response => {
                this.form = response;
            });
        },
        handleFilter() {
            this.page = 1;
            this.getList();
        },
        handleCreate() {
            this.formTitle = '新增库位';
            this.isEdit = false;
            this.dialogFormVisible = true;
        },
        handleDelete(row) {
            var params = [];
            let alert = '';
            if (row) {
                params.push(row.id);
                alert = row.name;
            }
            else {
                if (this.multipleSelection.length === 0) {
                    this.$message({
                        message: '未选择',
                        type: 'warning'
                    });
                    return;
                }
                this.multipleSelection.forEach(element => {
                    let id = element.id;
                    params.push(id);
                });
                alert = '选中项';
            }
            this.$confirm('是否删除' + alert + '?', '提示', {
                confirmButtonText: '确定',
                cancelButtonText: '取消',
                type: 'warning'
            }).then(() => {
                this.$axios.posts('/api/business/warehouseLocation/delete', params).then(response => {
                    this.$notify({
                        title: '成功',
                        message: '删除成功',
                        type: 'success',
                        duration: 2000
                    });
                    this.getList();
                });
            }).catch(() => {
                this.$message({
                    type: 'info',
                    message: '已取消删除'
                });
            });
        },
        handleUpdate(row) {
            this.formTitle = '修改库位';
            this.isEdit = true;
            if (row) {
                this.fetchData(row.id);
                this.dialogFormVisible = true;
            }
            else {
                if (this.multipleSelection.length != 1) {
                    this.$message({
                        message: '编辑必须选择单行',
                        type: 'warning'
                    });
                    return;
                }
                else {
                    this.fetchData(this.multipleSelection[0].id);
                    this.dialogFormVisible = true;
                }
            }
            // //加单位
            // this.form.locationLength = this.form.locationLength + 'm'; // 如果不为空且没有单位，则添加单位
            // this.form.locationWidth = this.form.locationWidth + 'm'; // 如果不为空且没有单位，则添加单位
            // this.form.locationHeight = this.form.locationHeight + 'm'; // 如果不为空且没有单位，则添加单位
            // // this.form.locationVolume += 'm³'; // 如果不为空且没有单位，则添加单位
            // this.form.loadBearing = this.form.loadBearing + 'kg'; // 如果不为空且没有单位，则添加单位
            console.log(this.form);
        },
        save() {
            // //去除单位
            // this.form.locationLength = this.form.locationLength.slice(0, -1); // 去掉最后一个字符 'm'
            // this.form.locationWidth = this.form.locationWidth.slice(0, -1); // 去掉最后一个字符 'm'
            // this.form.locationHeight = this.form.locationHeight.slice(0, -1); // 去掉最后一个字符 'm'
            // // this.form.locationVolume = this.form.locationVolume.slice(0, -2); // 去掉最后三个字符 'm³'
            // this.form.loadBearing = this.form.loadBearing.slice(0, -2); // 去掉最后两个字符 'kg'  
            this.$refs.form.validate(valid => {
                if (valid) {
                    this.formLoading = true;
                    this.form.roleNames = this.checkedRole;
                    if (this.isEdit) {
                        this.$axios.posts('/api/business/warehouseLocation/data-post', this.form).then(response => {
                            this.formLoading = false;
                            this.$notify({
                                title: '成功',
                                message: '更新成功',
                                type: 'success',
                                duration: 2000
                            });
                            this.dialogFormVisible = false;
                            this.getList();
                        }).catch(() => {
                            this.formLoading = false;
                        });
                    }
                    else {
                        this.form.pCode = this.onTreeData.id;
                        this.$axios.posts('/api/business/warehouseLocation/data-post', this.form).then(response => {
                            this.formLoading = false;
                            this.$notify({
                                title: '成功',
                                message: '新增成功',
                                type: 'success',
                                duration: 2000
                            });
                            this.dialogFormVisible = false;
                            this.getList();
                        }).catch(() => {
                            this.formLoading = false;
                        });
                    }
                }
            });
        },
        sortChange(data) {
            const {
                prop,
                order
            } = data;
            if (!prop || !order) {
                this.handleFilter();
                return;
            }
            this.listQuery.Sorting = prop + ' ' + order;
            this.handleFilter();
        },
        handleSelectionChange(val) {
            this.multipleSelection = val;
        },
        handleRowClick(row, column, event) {
            this.$refs.multipleTable.clearSelection();
            this.$refs.multipleTable.toggleRowSelection(row);
        },
        cancel() {
            this.form = Object.assign({}, defaultForm);
            this.dialogFormVisible = false;
            this.$refs.form.clearValidate();
        },
        //#endregion
    }
}

</script>
<style></style>
